/* eslint-disable no-debugger */
import { OnRouteBeforeType } from "@/components/RouterWaiter/types";
import { RootState, store } from "@/store";
import { useDispatch, useSelector } from "react-redux";
import { AxiosCanceler } from "@/utils/http/axios/axiosCancel";
import { getTitle } from "@/utils/envUtils";
import { PageEnum } from "@/enums/PageEnum";
import { setCurrentRoute } from "@/store/modules/global";
import useRouter from "@/hooks/useRouter";
const axiosCanceler = new AxiosCanceler();

/**
 * @description: 全局路由拦截
 * @param {string} pathname 当前路由路径
 * @param {object} meta 当前路由自定义meta字段
 * @return {string} 需要跳转到其他页时就return一个该页的path路径
 */
const onRouteBefore: OnRouteBeforeType = ({ pathname, meta }) => {
	axiosCanceler.removeAllPending();
	// eslint-disable-next-line no-debugger
	// debugger;
	const { authRouter } = useSelector((state: RootState) => state.auth);
	const { token } = useSelector((state: RootState) => state.global);
	// 动态修改页面title
	setTitle(meta.title);

	if (!meta.requiresAuth) {
		return;
	}
	if (!token) {
		// return PageEnum.BASE_LOGIN;
		return `${PageEnum.BASE_LOGIN}?redirectUrl=${encodeURIComponent(window.location.href)}`;
	}
	const message = `${pathname},${meta.title || ""}`;
	const path403 = `/403?message=${encodeURIComponent(message)}`;
	const staticRouter = [PageEnum.BASE_HOME, PageEnum.BASE_NO_AUTH];
	const routerList = authRouter.concat(staticRouter);
	if (routerList.indexOf(pathname) == -1) return path403;

	// // 登录及权限判断
	// if (!meta.noLogin) {
	// 	// 路由是否需要登录
	// 	if (userStore.isLogin) {
	// 		// 用户是否已登录
	// 		const { accessId } = meta;
	// 		const message = `${pathname},${meta.title || ""}`;
	// 		const path403 = `/403?message=${encodeURIComponent(message)}`;

	// 		if (!userStore.isGotUserInfo) {
	// 			// 是否已获取到用户（权限）信息
	// 			return new Promise(resolve => {
	// 				api.getUserInfo().then((res: any) => {
	// 					const data = res.data || {};
	// 					userStore.setUserInfo(data);

	// 					if (!getIsCanAccess(accessId)) {
	// 						resolve(path403);
	// 					}
	// 				});
	// 			});
	// 		} else {
	// 			if (!getIsCanAccess(accessId)) {
	// 				return path403;
	// 			}
	// 		}
	// 	} else {
	// 		return `/login?redirectUrl=${encodeURIComponent(window.location.href)}`;
	// 	}
	// }
};

const setTitle = (title: String) => {
	window.document.title = `${getTitle()} ${title ? " | " + title : ""}`;
};

export default onRouteBefore;
